import json

import requests
from django.conf import settings
from django.http import JsonResponse

# 图片转文本
def image_to_text(request):
    # 获取参数并校验参数
    fid = request.GET.get("fid")
    Authorization = request.headers.get("Authorization")
    if not fid:
        return JsonResponse({"code": 400, "msg": "fid参数不能为空"})
    elif not Authorization:
        return JsonResponse({"code": 400, "msg": "authorization error"})
    # 创建对哈
    chat_id = requests.get(settings.BLACK_AI_DOMAIN + "api/ai/kimi/v1/create_id/", headers={
        'Authorization': Authorization
    }).json()['data']['id']
    if not chat_id:
        return JsonResponse({"code": 400, "msg": "创建对哈失败"})

    # 制作提示词
    prompt = """
    请将图片中的文字翻译成中文。要求：
    1. 只返回翻译后的中文文本
    2. 不要添加任何前缀、后缀或修饰词
    3. 不要添加任何标点符号或特殊字符
    4. 不要添加任何说明或解释
    5. 如果无法识别，直接返回"无法识别图片中的文字"
    """
    params = {
        "chat_id": chat_id,
        "message": prompt,
        "refs": json.dumps([fid])
    }

    res = requests.get(settings.BLACK_AI_DOMAIN + "api/ai/kimi/v1/chat/completions/", headers={
        "Authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiY2IxODI4NDUtNTA3OC00ZmI0LWI3NmQtZjkzMzdjNDM0MWM3IiwiZXhwIjoxNzQ3OTc2NjczfQ._Pi_Xzu749jfpga_rk8s5qdX7ErxSMhxbFE8oyWkukU"
    }, stream=True, params=params)
    dst = ""
    for text in res.iter_lines():
        if text:
            text = text.decode("utf-8")
            text = text.replace("data: ", "")
            text = json.loads(text)
            if text['type'] == "comp":
                dst += text['msg']
    # 制作指定返回格式
    return JsonResponse({"code": 200, "msg": "获取AI翻译结果成功", "data": [
        {"dst": dst}
    ]})
